package com.leandom.studydemo.async.loader;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.loader.content.AsyncTaskLoader;

public class DemoAsyncTaskLoader extends AsyncTaskLoader<String> {

    private static final String TAG = "DEMO";

    public DemoAsyncTaskLoader(@NonNull Context context) {
        super(context);
        Log.d(TAG, "DemoAsyncTaskLoader(): " + this);
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        Log.d(TAG, "onStartLoading: " + isStarted());
        // 注意1：每次app从后台进入前台的时候onStartLoading也会执行
        // 注意2：需要调用以下方法才能执行loadInBackground
        forceLoad();
    }

    @Nullable
    @Override
    public String loadInBackground() {
        Log.d(TAG, "loadInBackground start...");
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            Log.e(TAG, "loadInBackground InterruptedException");
            e.printStackTrace();
        }
        Log.d(TAG, "loadInBackground finish");
        return "SUCCESS";
    }

    @Override
    public void deliverResult(@Nullable String data) {
        super.deliverResult(data);
        Log.d(TAG, "deliverResult: " + data);
    }
}
